package com.zgis.monitor.util;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 远程连耳服务器工具类
 */
@Slf4j
public class SshUtil
{
    /**
     * 执行远程命令
     */
    public static String executeCommand(String ip, int port, String username, String password, String command)
    {
        Session       session = null;
        ChannelExec   channel = null;
        StringBuilder result  = new StringBuilder();

        try
        {
            JSch jsch = new JSch();
            session = jsch.getSession(username, ip, port);
            session.setPassword(password);

            // 跳过HostKey检查
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            session.connect(30000); // 30秒超时

            // 执行命令
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);
            channel.setInputStream(null);
            channel.setErrStream(System.err);

            // 获取命令输出
            InputStream in = channel.getInputStream();
            channel.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String         line;
            while ((line = reader.readLine()) != null)
            {
                result.append(line).append("\n");
            }

            reader.close();
            channel.disconnect();
            session.disconnect();

        }
        catch (Exception e)
        {
            log.error("SSH命令执行失败: " + e.getMessage(), e);
            return "ERROR: " + e.getMessage();
        }
        finally
        {
            if (channel != null && channel.isConnected())
            {
                channel.disconnect();
            }
            if (session != null && session.isConnected())
            {
                session.disconnect();
            }
        }

        return result.toString().trim();
    }
}
    